<?php

namespace App\Services\Admin;

use App\Common\Helper;
use App\Dao\Lsv\MenuDao\Orm as MenuDao;
use App\Dao\Lsv\MenuAuthDao\Orm as MenuAuthDao;
use App\Dao\Lsv\MenuAuthButtonDao\Orm as MenuAuthButtonDao;
use App\Dao\Lsv\MenuAuthApiDao\Orm as MenuAuthApiDao;
use App\Dao\Lsv\MenuAuthPagesDao\Orm as MenuAuthPagesDao;
use App\Dao\Lsv\RoleDao\Orm as RoleDao;

class Role extends \App\Services\BaseService
{

    /**
     * @description:  获取用户权限
     * @param  int    $role_id   权限id
     * @return {*}
     */
    public static function getMenuButtons(int $role_id)
    {
        $result = [
            'menu'  => [],            //栏目
            'buttons'  => [],         //按钮权限
            // 'auth_pages'   => [],     //权限页面
        ];

        [$menu, $auth] = self::getRoleJson($role_id);

        /*  没有栏目显示并且不是超级管理员和开发者 空栏目  */
        if ($role_id > 0 && empty($menu)) return $result;



        /* 根据菜单menu_id生成树 */
        [$tree, $tmp] =  Helper::createTree(
            //空栏目时全查
            (new MenuDao)->inMenuIdOrAuth($menu,$auth)->menuSort()->menuIdSort()->end()->get(
                [
                    'menu_id',
                    'menu_pid',
                    'path',
                    'name',
                    'redirect',
                    'component',
                    'menu_sort',
                    'icon',
                    'title',
                    'isLink',
                    'isHide',
                    'isFull',
                    'isAffix',
                    'isKeepAlive'
                ]
            )->toArray(),
            'menu_id',
            'menu_pid',
            'children',
            function($item){
                if($item['menu_pid'] === null ) $item['menu_pid'] = 0;
                return $item;
            },
            true
        );
        /* */


        /* 栏目树  */
        $result['menu'] = $tree;
        /* */

        /* 没有权限并且不是超级管理员和开发者  */
        $auths = $role_id > 0 && empty($auth) ? [] : self::auth($tmp, $auth);
        /* */


        /* 有按钮权限才进行组装数据 */
        if (!empty($auths)) {
            /* 生成path => [buttons] 按钮权限数据 */
            $result['buttons'] = self::buttons($auths, $tmp);
            /* */
        }

        return  $result;
    }

    public static function getMenu(string $router_path){

        return (new MenuDao)->wherePath($router_path)->end()->first(['menu_id','menu_pid','auth_id']);

    }

    public static function getMenuApi(string $api)
    {
        return (new MenuAuthApiDao)->menuJoin()->menuAuthLeftJoin()->whereMenuAuthApi($api)->end()->first(['menu_auth_api.api_id', 'menu_auth_api.add_log', 'menu_auth.auth_id', 'menu.title', 'menu.menu_id', 'auth_name'])?->toArray();
    }

    public static function checkMenuApi(int $role_id, string $api)
    {

        // $menu = self::getMenu($route_path);

        // if(!$menu) return false;  //没有该栏目

        $menuApi =  self::getMenuApi( $api);

        if (!$menuApi) return null;  //没有加入权限

        $result = [
            'add_log' => $menuApi['add_log'],
            'auth_name' => $menuApi['auth_name'],
            'menu_title' => $menuApi['title'],
        ];
        if ($role_id <= 0) $result['check'] = true; //超级管理员和开发者或者验证成功
        else {
            $role_json =  (new RoleDao)->whereRole($role_id)->end()->first(['role_json'])->role_json;
            /* NULL 为栏目公共接口 */
            $result['check'] = isset($role_json[$menuApi['menu_id']]) && ($menuApi['auth_id'] === null  || in_array($menuApi['auth_id'], $role_json[$menuApi['menu_id']])) ? true : false;
        }

        return $result;
    }


    private static function auth($menu, $auth): array
    {

        return  empty($menu) ? [] :
        (new MenuAuthDao)->inMenuId($menu)->inAuthId($auth)->authSort()->authIdSort()->end()->get()->toArray();
    }


    private static function buttons($auth, $tmp): array
    {
        $buttons = [];
        /* 把auth_id变成key 顺便找到该权限的路径  */
        $auth = Helper::keyArray($auth, 'auth_id', function ($item) use ($tmp) {
            $item['path'] = $tmp[$item['menu_id']]['path'];
            return $item;
        });


        if (!empty($auth)) {
            foreach ((new MenuAuthButtonDao)->inAuthId($auth)->end()->get() as $val) {
                $buttons[$auth[$val->auth_id]['path']] ??  $buttons[$auth[$val->auth_id]['path']] = [];
                $buttons[$auth[$val->auth_id]['path']][] = $val->buttons;
            }
        }
        return $buttons;
    }

    private static function getRoleJson(int $role_id): array
    {
        $menu_id = [];
        $auth_id = [];
        if ($role_id > 0) {
           $role_json = (new RoleDao)->whereRole($role_id)->end()->first(['role_json'])?->role_json;
           if( $role_json){
            foreach ($role_json as $key => $val) {
                $menu_id[] = $key;
                $auth_id = array_merge($auth_id, $val);
            }
           }
        }
        return [$menu_id, $auth_id];
    }


    private static function getAuthPages(array $auth,int $role_id){

        $menuAuthPages = [];   // ['栏目id' => [ '页面'] ]

        $menuAuthPagesDao = new MenuDao;

        if( $role_id > 0){
            $menuAuthPagesDao  =  empty($auth)  ? null : $menuAuthPagesDao->whereInAuthId($auth);
        }else{
            $menuAuthPagesDao  = $menuAuthPagesDao->whereAuth();
        }


        if($menuAuthPagesDao){
            foreach($menuAuthPagesDao->end()->get() as $val){
                     if(!isset( $menuAuthPages[$val->menu_id] ) )  $menuAuthPages[$val->menu_id] = [];
                     $val->isHide = 1;   //权限页面隐藏在栏目显示
                     $val->makeHidden(['auth_id']);
                     $menuAuthPages[$val->menu_id][] = $val->toArray();
            }
        }


        return $menuAuthPages;
    }
}
